# Author: Michal 'mucha' Muszynski
# + Getting video download URLs by Damian 'Rush' Kaczmarek
# License: MIT

package GetTitle;
use base Module;
use strict;
use utf8;
use LWP::Simple;
use HTML::Entities;

my $get_youtube     = Config::get('youtube',       'true');
my $get_videogoogle = Config::get('videogoogle',   'true');
my $get_imdb        = Config::get('imdb',          'true');

sub get_title
{
	my $text = shift;

	my $msg;
	if ($get_youtube =~ /true/i && $text =~ /(\bhttp:\/\/(?:www\.|pl\.|uk\.|)?youtube.com\/watch\S+)/) {
		my $link = $1;

		my $dump = get($link);
		print $dump;
		if (defined $dump) {
#			$dump =~ m/<title>YouTube - (.*?)<\/title>/;
			$dump =~ m/document.title = 'YouTube - (.*?)';/;

			$msg = Util::bold("[YouTube] ") . decode_entities($1);
			return $msg;
		}
	}
	elsif (    $get_videogoogle =~ /true/i
		&& $text =~ /(\bhttp:\/\/video.google.(co.uk|com|pl)\/videoplay\?docid=\S+)/) {
		my $link = $1;
		my $dump = get($link);
		if (defined $dump) {
			$dump =~ m/<title>(.*?)<\/title>/;
			$msg = Util::bold("[Google Video] ") . decode_entities($1);
			return $msg;
		}
	}
	elsif (    $get_imdb =~ /true/i
		&& $text =~ /(\bhttp:\/\/(www.|us.|)imdb.com\/(name|character|title)\/\w+( |\/ |$|\/$))/) {
		my $link = $1;
		my $dump = get($link);
		if (defined $dump) {
			$dump =~ m/<title>(.*?)<\/title>/;
			return Util::bold("[IMDb] ") . decode_entities($1);
		}
	}
}

sub on_public
{
	my $text = $_[1];
	Core::send_msg(get_title($text));
}
1;